﻿using AutoMapper;
using B.S.DataBase.MyProject.Domain;
using B.S.DataBase.MyProject.ErrorCode;
using B.S.DataBase.MyProject.Infrastructure.Interface;
using B.S.DataBase.MyWrite.API.Appicant.Command.MenuCommand;
using MediatR;
using Microsoft.AspNetCore.Http;

namespace B.S.DataBase.MyWrite.API.Appicant.CommandHandler.MenuCommandHandler
{
    /// <summary>
    /// 添加菜单命令执行
    /// </summary>
    public class AddMenuCommandHandler : IRequestHandler<AddMenuCommand, APIResult<string>>
    {
        private readonly IBaseRepository<MenuModel> menuRepos;
        private readonly IMapper mapper;

        public AddMenuCommandHandler(IBaseRepository<MenuModel> menuRepos,IMapper mapper)
        {
            this.menuRepos = menuRepos;
            this.mapper = mapper;
        }


        /// <summary>
        /// 添加菜单
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<APIResult<string>> Handle(AddMenuCommand request, CancellationToken cancellationToken)
        {
            APIResult<string> result = new APIResult<string>();
            var list = menuRepos.GetAll().Result.ToList().Count();
            var model = mapper.Map<MenuModel>(request);
            model.OrderNum = ++list;
            var res =  menuRepos.Add(model).Result;
            //成功
            if (res > 0)
            {
                result.Code = APIEnum.添加成功;
                result.Msg = APIEnum.添加成功.ToString();
                result.data = res.ToString();
            }else
            {
                result.Code = APIEnum.添加失败;
                result.Msg = APIEnum.添加失败.ToString();
            }
            return await Task.FromResult(result);
        }
    }
}
